<?php

namespace App\Services\Third;

use App\Http\Request;
use App\Models\ApiLog;

class LogDb
{

    private $model;

    /**
     * @param \Illuminate\Http\Request $request
     * @return $this
     */
    public function apiStart($request)
    {
        $this->model = new ApiLog();
        $params      = $this->model->asJson($request->all());

        $this->model->ip_address = $request->getClientIp();
        $this->model->params     = strlen($params) > 9999 ? '' : $params;
        $this->model->uri        = $request->getPathInfo();
        $this->model->method     = $request->method();
        $this->model->sign       = Request::getSign() ?? '';
        $this->model->start_time = get_m_sec_time();
        $this->model->client     = Request::getAppId() ?? '';
        return $this;
    }

    /**
     * @param $response
     * @return ApiLog|bool
     * @name:apiFinish
     * @author: lisa
     * @datetime: 2022/3/4 9:12
     */
    public function apiFinish($response)
    {
        $responseContent = json_decode($response->getContent(), true);
        /** @var ApiLog $model */
        $model = $this->model;
        if (mb_strlen($response->getContent(), 'utf-8') > 9999) {
            $responseContent = [
                'code'    => $response->getStatusCode(),
                'message' => isset($responseContent['message']) ? $model->asJson($responseContent['message']) : '',
                'data'    => new \ArrayObject()
            ];
        }
        $model->end_time    = get_m_sec_time();
        $model->con_time    = $model->end_time - $model->start_time;
        $model->res_code    = $responseContent['code'] ?? $response->getStatusCode();
        $model->res_msg     = isset($responseContent['message']) ? $model->asJson($responseContent['message']) : '';
        $model->res_content = $model->asJson($responseContent);
        $model->user_id     = user(false)->userId();
        $model->save();
        return $model;
    }
}
